package com.example.demo;

import org.springframework.web.bind.annotation.*;
import java.net.*;
import java.io.*;
import java.util.*;
import com.alibaba.fastjson.*;
import javax.servlet.http.*;

@RestController
public class QQController{
  @GetMapping("/qqlogin")
  public void qqlogin(String token,HttpServletResponse res)throws Exception{
    String url = "https://graph.qq.com/oauth2.0/me?access_token="+token;
    String html = getHTML(url);
    String startStr = "openid";
    int start = html.indexOf(startStr);
    int end = html.lastIndexOf("\"");
    String openid = html.substring(start+9,end);
    String qqinfourl = "https://graph.qq.com/user/get_user_info?access_token="+token+"&oauth_consumer_key=101960277&openid="+openid;
   // return getHTML(qqinfourl);    
    JSONObject qqInfo = JSON.parseObject(getHTML(qqinfourl));
    System.out.println(qqInfo.getString("nickname"));
    res.sendRedirect("index.html?nickname="+qqInfo.getString("figureurl_qq_1")); 
  }

  public String getHTML(String urlstr)throws Exception{
    URL url = new URL(urlstr);
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
    String s;
    String ss = "";
    while((s=br.readLine())!=null){
      ss+=s;
    }
    br.close();
    con.disconnect();
    return ss;   
  }
}
